/*
 * @Author: Leo.wang wanglizhigs@163.com
 * @Date: 2024-09-02 22:47:16
 * @LastEditors: Leo.wang wanglizhigs@163.com
 * @LastEditTime: 2024-09-03 22:52:12
 * @FilePath: /metaverse-manage/app/controller/Manager.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import { Controller } from 'egg';
import { response } from '../utils/common';
import { initManager, updateManager } from '../entity/Manager';
import jwt from 'jsonwebtoken';
// import md5 from 'crypto-js/md5';


export default class ManagerController extends Controller {
  // 查询所有
  public async queryAllManagers() {
    const { ctx } = this;
    const result = await ctx.service.manager.queryAllManagers();
    ctx.body = response(result);
  }
  public async queryManagerById() {
    const { ctx } = this;
    const { id } = ctx.params;
    const result = await ctx.service.manager.queryManagerById(Number(id));
    ctx.body = response(result);
  }


  public async createManager() {
    const { ctx } = this;
    const manager = initManager({ ...ctx.request.body });
    const result = await ctx.service.manager.createManager(manager);
    ctx.body = response(result);
  }
  public async updateManager() {
    const { ctx } = this;
    const { id } = ctx.params;
    const manager = updateManager({ ...ctx.request.body });
    const result = await ctx.service.manager.updateManager(Number(id), manager);
    ctx.body = response(result);
  }
  public async removeManager() {
    const { ctx } = this;
    const { id } = ctx.params;
    const result = await ctx.service.manager.removeManager(Number(id));
    ctx.body = response(result);
  }


  public async login() {
    const { ctx } = this;
    const { username, password } = ctx.request.body;

    // const pwd = md5(password).toString();
    // console.log('pwd', pwd);

    // console.log('this.config.jwt.secret', this.config.jwt, username, password);
    const user = await ctx.service.manager.login(username, password);

    if (!user) {
      ctx.body = response('用户名或密码错误！', 401);
    } else {
      const token = jwt.sign({ id: user.id, username: user.username }, this.config.jwt.secret, { expiresIn: '1h' });
      ctx.body = response({
        token,
        user,
      });
    }

  }

}

